/*
 * Copyright (c) 2017. 杭州端点网络科技有限公司.  All rights reserved.
 */

package com.jiantong.admin.interceptor;

import com.jiantong.admin.ext.WebLoginUser;
import com.jiantong.common.model.BaseLoginUser;
import com.jiantong.user.model.OrganizationUser;
import com.jiantong.user.model.User;
import com.jiantong.user.model.UserProfile;
import com.jiantong.user.service.OrganizationUserReadService;
import com.jiantong.user.service.UserProfileReadService;
import com.jiantong.user.service.UserReadService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : panxin
 */
@Slf4j
@Component
public class AdminLoginInterceptor extends HandlerInterceptorAdapter {

    @RpcConsumer
    private UserReadService<User> userReadService;

    @RpcConsumer
    private UserProfileReadService userProfileReadService;

    @RpcConsumer
    private OrganizationUserReadService organizationUserReadService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("login interceptor, request = {}, \r\n response = {}", request, response);
//
//        Cookie[] cookies = null;
//        cookies = request.getCookies();
//        Long userId = null;
//        for (Cookie cookie : cookies) {
//            if (cookie.getName().equals("djtid")) {
//                userId = Long.parseLong(cookie.getValue());
//                break;
//            }
//        }
//        if(userId == null){
//            log.error("please login again");
//            throw new OPClientException("user id is null");
//        }
//        Response<User> userResponse = userReadService.findUserByUserId(userId);
//        if(!userResponse.isSuccess()){
//            log.error("user not found by user id");
//            throw new OPServerException("user not found by user id");
//        }
//
//        WebLoginUser webLoginUser= (WebLoginUser) warpLoginUser(userResponse.getResult(),userId);
//
//        UserUtil.putCurrentUser(webLoginUser);
        return true;
    }

    private BaseLoginUser warpLoginUser(User user ,Long userId) {
        WebLoginUser webLoginUser = new WebLoginUser();
        webLoginUser.setUserId(userId);
        webLoginUser.setAreaLevel(user.getAreaLevel());
        webLoginUser.setStatus(user.getStatus());

        Response<UserProfile> userProfileResponse = userProfileReadService.findUserProfileById(userId);
        if(!userProfileResponse.isSuccess()){
            log.error("failed to find user profile , case = {}",userProfileResponse.getError());
            return webLoginUser;
        }

        webLoginUser.setUserProfile(userProfileResponse.getResult());

        Response<OrganizationUser> resp = organizationUserReadService.findOrganizationUserByUserId(userId);
        if (!resp.isSuccess()) {
            log.error("failed to find organization user by user id = {}, cause : {}", userId, resp.getError());
            return webLoginUser;
        }
        OrganizationUser organizationUser = resp.getResult();

        webLoginUser.setOrganizationId(organizationUser.getOrganizationId());
        webLoginUser.setOrganizationName(organizationUser.getOrganizationName());
        webLoginUser.setOrganizationType(organizationUser.getOrganizationType());

        List<Long> breedFactoryIds = new ArrayList<>();
        List<Long> butcherFactoryIds = new ArrayList<>();
        List<Long> declareStationIds = new ArrayList<>();
        List<Long> certificateStationIds = new ArrayList<>();


        return webLoginUser;
    }

}
